from django.http import JsonResponse
from django.shortcuts import render, redirect, reverse

from articles.models import *


# Create your views here.
def categories(request):
    categories = Category.objects.all()
    return render(request, "category.html", locals())


def add_categories(request):
    if request.method == "POST":
        print(111111)
        name = request.POST.get("name")
        describe = request.POST.get("describe")
        print(name, describe)
        # 写入数据库
        Category.objects.create(description=describe, cname=name)
        return redirect(reverse("categories:add_categories"))
    else:
        categories = Category.objects.all()
        return render(request, "category.html", locals())


# 修改栏目
def update_category(request,cid):
    categories = Category.objects.get(pk=cid)
    if request.method == "POST":
        categories.cname = request.POST.get("name")
        categories.description = request.POST.get("describe")
        categories.save()
        return redirect(reverse("categories:categories"))
    else:
        print(categories.cname)
        print("*"*100)
        return render(request, "update-category.html",locals())

# 删除栏目
def delete_category(request,cid):
    categories = Category.objects.get(pk=cid)
    categories.delete()
    return redirect(reverse("categories:categories"))
def get_category(request):
    categories = Category.objects.all()
    categories = [item.to_dict() for item in categories]
    return JsonResponse({"categories": categories,"code":100})
def show_example(request):
    return render(request,"example1.html")